package com.manster.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.math.MathUtil;
import cn.hutool.core.util.RandomUtil;
import com.google.code.kaptcha.Producer;
import com.manster.entity.SysUser;
import com.manster.entity.SysUserRole;
import com.manster.util.Const;
import com.manster.util.R;
import com.manster.vo.EmailVo;
import com.manster.vo.RegisterUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.UUID;

/**
 * @Author manster
 * @Date 2022/3/13
 **/
@Slf4j
@RestController
@Api(tags = "认证")
public class AuthController extends BaseController {

    @Autowired
    private Producer producer;

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

    @GetMapping("/captcha")
    @ApiOperation(value = "获取验证码")
    public R captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String code = producer.createText();
        String key = UUID.randomUUID().toString();

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());

        // 存储到redis中,有效时间两分钟
        redisUtils.hset(Const.CAPTCHA_KEY, key, code, 120);
        log.info("验证码 -- {} - {}", key, code);
        return R.success().data(
                MapUtil.builder()
                        .put("token", key)
                        .put("captchaImg", base64Img)
                        .build()
        );
    }

    @ApiOperation("登录后获取当前用户信息")
    @GetMapping("/sys/userInfo")
    public R userInfo(Principal principal){
        SysUser user = userService.getByUsername(principal.getName());

        return R.success().data(MapUtil.builder()
            .put("id",user.getId())
            .put("username",user.getUsername())
            .put("avatar",user.getAvatar())
            .map()
        );
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public R register(@Validated @RequestBody RegisterUserVo registerUserVo){
        //从redis获取该邮箱对应的验证码
        String redisCode = (String) redisUtils.get(registerUserVo.getEmail());
        //验证码正确
        if(redisCode.equals(registerUserVo.getCode())){
            SysUser user = new SysUser();
            BeanUtils.copyProperties(registerUserVo,user);
            user.setPassword(passwordEncoder.encode(registerUserVo.getPassword()));
            //设置默认头像
            user.setAvatar(Const.DEFAULT_AVATAR);
            user.setStatus(1);
            userService.save(user);
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getId());
            //默认设为普通用户
            userRole.setRoleId(3L);
            userRoleService.save(userRole);
            return R.success().data("注册成功");
        }
        return R.fail().data("验证码错误，注册失败");
    }

    @ApiOperation("发送邮箱验证码")
    @GetMapping("/sendEmail/{email}")
    public R register(@PathVariable("email") String email){
        //根据邮箱获取用户
        SysUser user = userService.getByEmail(email);
        if(user==null){
            String code = RandomUtil.randomNumbers(5);
            //存储120秒
            redisUtils.set(email,code,120);
            String content = "欢迎注册杭州市IT人才需求地图信息系统，注册验证码为:" + code;
            EmailVo emailVo = new EmailVo(new String[]{email},"用户注册验证码", content);
            return commonEmail(emailVo);
        }
        return R.fail().data("该邮箱已被注册，请更换邮箱后再次进行注册");
    }

    public R commonEmail(EmailVo toEmail) {
        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //谁发的
        message.setFrom(from);
        //谁要接收
        message.setTo(toEmail.getTos());
        //邮件标题
        message.setSubject(toEmail.getSubject());
        //邮件内容
        message.setText(toEmail.getContent());
        try {
            mailSender.send(message);
            return R.success().data("发送邮件成功");
        } catch (MailException e) {
            e.printStackTrace();
            return R.fail().data("邮件发送失败");
        }
    }

}
